﻿using IService.Admin;
using Model.Enums.Admin;

namespace Service.Tasks
{
    public class HangFireService : IService.Tasks.IHangFireService
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        private readonly IRedisService _redisService;

        private readonly IEnumHelperService _EnumHelper;
        private readonly IAdminService _adminService;
        private static readonly object _locker = new();

        public HangFireService(ISqlSugarClient sqlSugarClient, IRedisService redisService, IAdminService adminService, IEnumHelperService enumHelperService)
        {
            _sqlSugarClient = sqlSugarClient;
            _redisService = redisService;
            _EnumHelper = enumHelperService;
            _adminService = adminService;
        }

        /// <summary>
        /// 自动构建Redis缓存
        /// </summary>
        /// <returns></returns>
        public async Task AutoBuildRedis()
        {
            await Console.Out.WriteLineAsync("AutoBuildRedis\t" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            _adminService.SetI18n();
        }

        #region 后台消息推送

        /// <summary>
        /// 后台消息推送
        /// </summary>
        /// <returns></returns>
        public async Task AutoSendMessage()
        {
            Console.WriteLine("AutoSendMessage\t" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            var db = _sqlSugarClient;
            var orders = await db.Queryable<TMessage>().Where(o => !o.IsSend).ToListAsync();
            var admins = await db.Queryable<TAdminInfo>().Where(o => o.Status == (int)Enum_AdminStatus.Working).Select(o => o.Id).ToListAsync();
            orders.ForEach(item =>
            {
                admins.ForEach(ad =>
                {
                    db.Insertable(new TAdminMessageRelation { AdminId = ad, MsgId = item.Id, Status = (int)Enum_MessageStatus.unread }).ExecuteCommand();
                });
                item.IsSend = true;
                db.Updateable(item).ExecuteCommand();
            });
        }

        #endregion 后台消息推送
    }
}